//
//  AY_BookQianDPage.m
//  AiYue
//
//  Created by boWen on 2023/11/2.
//

#import "AY_BookQianDPage.h"
#import "AY_BookQianDCell1.h"
#import "AY_BookQianDCell2.h"
#import "AY_BookQDHeaderView.h"
#import "AY_BookQdAlertView.h"
#import "AY_BookVpPage.h"
#import "AY_SignTaskTableViewCell.h"
#import "AY_MainTabViewController.h"
#import "AY_StimulateAd.h"
@interface AY_BookQianDPage ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) AY_StimulateAd *rewardedVideoAd;
@property (nonatomic, strong) UITableView * baseTableView;
@property (nonatomic, strong) AY_BookQDHeaderView * sxQdHeaderView;
@property (nonatomic, strong) NSArray * qdList;
@property (nonatomic, strong) NSMutableArray * taskList;
@property (nonatomic, strong) SignOwnModel * signModel;
@property (nonatomic, strong) SignRewardModel * rewardModel;
@property (nonatomic, strong) AY_BookQdAlertView * qdAlertView;
@property (nonatomic, strong) UserInfo * userInfoModel;//用户积分
@property (strong,nonatomic) AY_LoadingView *loadingView;
@end

@implementation AY_BookQianDPage

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getConfigWithData];//签到列表
    [self userInfoNew];//用户积分数
    [self qdNet];//签到
    [self getTaskList]; // 任务列表
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initWithNav];
}


- (void)initWithNav {
    self.gk_navigationBar.hidden = YES;
    [self.view addSubview:self.baseTableView];
    self.view.backgroundColor = [AYTool customJianBianColorWithColor0:COLOR(@"#F7DCBC") withColor1:COLOR(@"#FDF6E9") withFrame:CGSizeMake(GK_SCREEN_WIDTH, GK_SCREEN_HEIGHT) withType:1];
}


- (void)getConfigWithData {
    [AYApiRequest getSignActivityItemsSuccess:^(AY_PaQianDModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.qdList = pkg.data;
            [self.baseTableView reloadData];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)userInfoNew {
    [AYApiRequest getUserInfoSuccess:^(AY_UserModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.userInfoModel = pkg.data;
            self.sxQdHeaderView.goldNum = self.userInfoModel.goldNum;
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)getTaskList
{
    [AYApiRequest getTaskListWithSuccess:^(AY_TaskModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.taskList = pkg.data;
            for (AY_TaskListModel *listModel in self.taskList) {
                listModel.isSelect = @"0";
            }
            [self.baseTableView reloadData];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)taskCommitWithTaskID:(NSString *)taskId withSuccess:(void (^)(AY_CommitTask * _Nonnull pkg))success
{
    [self.loadingView loadingInView:self.view];
    [AYApiRequest taskCommitWithTaskId:taskId andWithTaskItemId:@"" andWithcommitParamJson:@"" andWithSuccess:^(AY_CommitTask * _Nonnull pkg) {
        [self.loadingView dismiss];
        if([pkg.code isEqualToString:@"200"]) {
            // 提交成功
            [self getTaskList];
            [self userInfoNew];//用户积分数
            if (success) {
                success(pkg);
            }
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
        [self.loadingView dismiss];
    }];
}

//当天签到
- (void)qdNet {
    [AYApiRequest getUserSignUpSuccess:^(AY_SignUpModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.rewardModel = pkg.data;
            self.qdAlertView.rewordjib = self.rewardModel.rewardGold;
            [self.qdAlertView showPopView];
        }
        [self getQdMessage];
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}
//获取用户签到信息
- (void)getQdMessage {
    [AYApiRequest getUserSignDetailSuccess:^(AY_SignModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.signModel = pkg.data;
            self.sxQdHeaderView.signModel = self.signModel;
        }
        [self.baseTableView reloadData];
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (UITableView *)baseTableView {
    if (!_baseTableView) {
        UITableView * myTableView = [AYTool creatMyTableView:CGRectMake(0, 0, GK_SCREEN_WIDTH, GK_SCREEN_HEIGHT)];
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.backgroundColor = [UIColor clearColor];
        myTableView.tableHeaderView = self.sxQdHeaderView;
        [myTableView registerClass:[AY_BookQianDCell1 class] forCellReuseIdentifier:@"AY_BookQianDCell1"];
        [myTableView registerClass:[AY_BookQianDCell2 class] forCellReuseIdentifier:@"AY_BookQianDCell2"];
        [myTableView registerClass:[AY_SignTaskTableViewCell class] forCellReuseIdentifier:@"AY_SignTaskTableViewCell"];
        
        

        _baseTableView = myTableView;
    }
    return _baseTableView;
}

- (NSArray *)qdList {
    if(!_qdList) {
        _qdList = [NSArray array];
    }
    return _qdList;
}


- (AY_BookQDHeaderView *)sxQdHeaderView {
    if(!_sxQdHeaderView) {
        _sxQdHeaderView = [[AY_BookQDHeaderView alloc] initWithFrame:CGRectMake(0, 0, GK_SCREEN_WIDTH, YNUM(170) + GK_STATUSBAR_NAVBAR_HEIGHT)];
    }
    return _sxQdHeaderView;
}

- (AY_BookQdAlertView *)qdAlertView {
    if(!_qdAlertView) {
        _qdAlertView = [[AY_BookQdAlertView alloc] initWithFrame:CGRectMake(0, 0, GK_SCREEN_WIDTH, GK_SCREEN_HEIGHT)];
        Weak_Self
        _qdAlertView.fanbeiBlock = ^{
            if ([weakSelf.qdAlertView.bottomTitle isEqualToString:@"继续领取"]) {
                // 视频任务
                [weakSelf.loadingView loadingInView:weakSelf.view];
                [weakSelf.rewardedVideoAd p_buildAdAndWithVC:weakSelf andWithStatusBlock:^(BOOL status) {
                    [weakSelf.loadingView dismiss];
                    [weakSelf.baseTableView reloadData];
                } andWithRewardDidSucceed:^(BOOL success) {
                    if (success) {
                        [weakSelf taskCommitWithTaskID:weakSelf.qdAlertView.extProperty withSuccess:^(AY_CommitTask *commitModel){
                            CommitTask *taskModel = commitModel.data;
                            if ([taskModel.toParticipateCount intValue]>0) {
                                if ([taskModel.rewardType isEqualToString:@"a_bean"]) {
                                    //书豆
                                    weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@书豆",taskModel.rewardAmount];
                                }else if ([taskModel.rewardType isEqualToString:@"a_gold"]){
                                    //金币
                                    weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@金币",taskModel.rewardAmount];
                                }else{
                                    //vip
                                    if ([taskModel.rewardUnit isEqualToString:@"days"]) {
                                        weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@天",taskModel.rewardAmount];
                                    }else if ([taskModel.rewardUnit isEqualToString:@"hours"]){
                                        weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@小时",taskModel.rewardAmount];
                                        
                                    }else if ([taskModel.rewardUnit isEqualToString:@"mins"]){
                                        weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@分钟",taskModel.rewardAmount];
                                        
                                    }
                                    
                                }
                               
                                weakSelf.qdAlertView.bottomTitle = @"继续领取";
                                [weakSelf.qdAlertView showPopView];
                            }else{
                                weakSelf.qdAlertView.bottomTitle = @"关闭";
                                [weakSelf.qdAlertView showPopView];
                            }
                            
                        }];
                    }
                }];
                
            }else if ([weakSelf.qdAlertView.bottomTitle isEqualToString:@"关闭"]){
                // 视频或其他任务
                [weakSelf.qdAlertView dismissPopView];
            }else{
                AY_BookVpPage * page = [[AY_BookVpPage alloc] init];
                [weakSelf.navigationController pushViewController:page animated:YES];
            }
            
        };
    }
    return _qdAlertView;
}



#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0){
        return 1;
    }else{
        return [self.taskList count];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        AY_BookQianDCell1 * cell = [tableView dequeueReusableCellWithIdentifier:@"AY_BookQianDCell1"];
        if(self.qdList.count > 0) {
            cell.qdList = self.qdList;
        }
        cell.signModel = self.signModel;
        Weak_Self
        cell.refreshBlock = ^{
            [weakSelf getQdMessage];
        };
        return cell;
    }else {
        
        AY_SignTaskTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AY_SignTaskTableViewCell"];
        if(self.taskList.count > 0) {
            AY_TaskListModel *listModel = self.taskList[indexPath.row];
            if(indexPath.row == 0){
                listModel.isFist = @"1";
            }
            if(indexPath.row == [self.taskList count] - 1){
                listModel.isLast = @"1";
            }
            cell.taskModel = self.taskList[indexPath.row];
            Weak_Self;
            cell.finishBlock = ^(AY_TaskListModel *model){
                if([model.finished isEqualToString:@"1"]){
                    // 已完成
                    if([model.rewardAcquired isEqualToString:@"0"]){
                        // 没有领取
                        [weakSelf taskCommitWithTaskID:model.taskId withSuccess:^(AY_CommitTask *commitModel){
                            CommitTask *taskModel = commitModel.data;
                            weakSelf.qdAlertView.extProperty = model.taskId;
                            if ([taskModel.rewardType isEqualToString:@"a_bean"]) {
                                //书豆
                                weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@书豆",taskModel.rewardAmount];
                            }else if ([taskModel.rewardType isEqualToString:@"a_gold"]){
                                //金币
                                weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@金币",taskModel.rewardAmount];
                            }else{
                                //vip
                                if ([taskModel.rewardUnit isEqualToString:@"days"]) {
                                    weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@天",taskModel.rewardAmount];
                                }else if ([taskModel.rewardUnit isEqualToString:@"hours"]){
                                    weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@小时",taskModel.rewardAmount];
                                    
                                }else if ([taskModel.rewardUnit isEqualToString:@"mins"]){
                                    weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@分钟",taskModel.rewardAmount];
                                    
                                }
                                
                            }
                            
                            weakSelf.qdAlertView.bottomTitle = @"关闭";
                            [weakSelf.qdAlertView showPopView];
                        }];
                    }
                }else{
                    // 没有完成
                    if([model.taskType isEqualToString:@"ggsp"]){
                        // 看视频
                        model.isSelect = @"1";
                        __weak AY_TaskListModel *weakModel = model;
                        [weakSelf.loadingView loadingInView:weakSelf.view];
                        [weakSelf.rewardedVideoAd p_buildAdAndWithVC:weakSelf andWithStatusBlock:^(BOOL status) {
                            [weakSelf.loadingView dismiss];
                            weakModel.isSelect = @"0";
                            [weakSelf.baseTableView reloadData];
                        } andWithRewardDidSucceed:^(BOOL success) {
                            if (success) {
                                [weakSelf taskCommitWithTaskID:model.taskId withSuccess:^(AY_CommitTask *commitModel){
                                    CommitTask *taskModel = commitModel.data;
                                    if ([taskModel.toParticipateCount intValue]>0) {
                                        weakSelf.qdAlertView.extProperty = model.taskId;
                                        
                                        if ([taskModel.rewardType isEqualToString:@"a_bean"]) {
                                            //书豆
                                            weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@书豆",taskModel.rewardAmount];
                                        }else if ([taskModel.rewardType isEqualToString:@"a_gold"]){
                                            //金币
                                            weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@金币",taskModel.rewardAmount];
                                        }else{
                                            //vip
                                            if ([taskModel.rewardUnit isEqualToString:@"days"]) {
                                                weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@天",taskModel.rewardAmount];
                                            }else if ([taskModel.rewardUnit isEqualToString:@"hours"]){
                                                weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@小时",taskModel.rewardAmount];
                                                
                                            }else if ([taskModel.rewardUnit isEqualToString:@"mins"]){
                                                weakSelf.qdAlertView.rewordjib = [NSString stringWithFormat:@"%@分钟",taskModel.rewardAmount];
                                                
                                            }
                                            
                                        }
                                       
                                        weakSelf.qdAlertView.bottomTitle = @"继续领取";
                                        
                                        [weakSelf.qdAlertView showPopView];
                                    }else{
                                        weakSelf.qdAlertView.bottomTitle = @"关闭";
                                        [weakSelf.qdAlertView showPopView];
                                    }
                                    
                                }];
                            }
                        }];
                        [weakSelf.baseTableView reloadData];
                        
                    }else if ([model.taskType isEqualToString:@"ydjl"]){
                        // 阅读赚金币
                        [weakSelf.navigationController popViewControllerAnimated:NO];
                        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
                        UINavigationController *nav = (UINavigationController *) window.rootViewController;
                        AY_MainTabViewController *rootViewController = nav.viewControllers[0];
                        [rootViewController setSelectedIndex:1];
                    }else if ([model.taskType isEqualToString:@"tz"]){
                        // 限时兑换
                        NSString *dicJumpStr = model.taskConfig;
                        NSDictionary *dicJump = [NSJSONSerialization JSONObjectWithData:[dicJumpStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
                        if(dicJump){
                            if([dicJump[@"jumpType"] isEqualToString:@"8"]){
                                AY_WebViewController *webVC = [[AY_WebViewController alloc] init];
                                webVC.fullPath = dicJump[@"jumpTarget"];
                                [weakSelf.navigationController pushViewController:webVC animated:YES];
                            }else if([dicJump[@"jumpType"] isEqualToString:@"10"]){
                                NSURL * url = [NSURL URLWithString:dicJump[@"jumpTarget"]];
                                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
                            }
                        }
                    }
                }
            };
        }
        return cell;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.section == 0 ? YNUM(233) : (indexPath.row == 0?YNUM(120):YNUM(72));
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 0 ? 0 : YNUM(12);
}

- (AY_StimulateAd *)rewardedVideoAd
{
    if (!_rewardedVideoAd) {
        _rewardedVideoAd = [AY_StimulateAd new];
    }
    return _rewardedVideoAd;
}

- (AY_LoadingView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[AY_LoadingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _loadingView.customImageView.center = CGPointMake(CGRectGetWidth(_loadingView.frame)/2, CGRectGetHeight(_loadingView.frame)/2 - 60);
        _loadingView.customImageView.bounds = CGRectMake(0, 0, 24, 24);
        _loadingView.infoLab.text = @"加载中";
        _loadingView.infoLab.textColor = [UIColor whiteColor];
        _loadingView.infoLab.font = YFont(12);
        [_loadingView.infoLab mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_loadingView.customImageView.mas_bottom).offset(YNUM(4));
        }];
        UIView *view = [[UIView alloc]initWithFrame:CGRectZero];
        view.center = CGPointMake(CGRectGetWidth(_loadingView.frame)/2, CGRectGetHeight(_loadingView.frame)/2 - 50);
        view.bounds = CGRectMake(0, 0, 90, 90);
        view.backgroundColor = [UIColor blackColor];
        view.alpha = 0.6;
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 12;
        [_loadingView addSubview:view];
        [_loadingView sendSubviewToBack:view];
        _loadingView.backgroundColor = [UIColor clearColor];
        _loadingView.hideLeftpop = YES;
    }
    return _loadingView;
}

@end
